<template>
  <div class="container">
    <div class="achieve-body">
      <el-button class="tabs-button" @click="toAdd">
        添加
      </el-button>
      <transition name="el-zoom-in-top">
        <el-card v-show="isShow" class="tabs-add-form">
          <el-form ref="achieveAddForm" :model="form" label-width="auto" size="small" :rules="rules">
            <el-form-item label="时间：" class="tabs-add-form-item" prop="achieveTime">
              <el-date-picker type="month" placeholder="选择日期" v-model="form.achieveTime" value-format="timestamp"></el-date-picker>
            </el-form-item>
            <el-form-item label="子项：" class="tabs-add-form-item" prop="achieveId">
              <el-select v-model="form.achieveId" placeholder="请选择" @change="selectChangeHandler">
                <el-option v-for="item in tabs.achievements" :key="item.id" :label="item.achieveName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数量：" class="tabs-add-form-item" prop="achieveNumber">
              <el-input-number v-model="form.achieveNumber" :min="selectFormInputNumber.minNumber" :max="selectFormInputNumber.maxNumber"></el-input-number>
            </el-form-item>
            <el-form-item label="备注：" class="tabs-add-form-item">
              <el-input v-model="form.remark" clearable></el-input>
            </el-form-item>
            <el-form-item class="tabs-add-form-item" style="clear: both">
              <el-button type="primary" @click="add(form, 'achieveAddForm')" :loading="buttonLoading">
                确定
              </el-button>
              <el-button type="info" @click="form = {}">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </transition>
      <el-dialog
          title="修改"
          :visible.sync="dialogVisible"
          :append-to-body="true"
          width="30%">
        <el-form :model="updateForm" label-width="auto" size="small">
          <el-form-item label="时间：">
            <el-date-picker type="month" placeholder="选择日期" v-model="updateAchieveTime" value-format="timestamp"></el-date-picker>
          </el-form-item>
          <el-form-item label="子项：">
            <el-select v-model="updateForm.achieveId" placeholder="请选择">
              <el-option v-for="item in tabs.achievements" :key="item.id" :label="item.achieveName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="绩点数：">
            <el-input-number v-model="updateForm.achieveNumber" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="update" :loading="updateButtonLoading">
              确定
            </el-button>
            <el-button type="info" @click="dialogVisible = !dialogVisible">
              取消
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-table
          :data="tableData"
          style="width: 100%">
        <el-table-column
            prop="achieveTime"
            label="月份"
            width="180"
            :formatter="timeFormat">
        </el-table-column>
        <el-table-column
            prop="achieveId"
            label="子项"
            width="180"
            :formatter="achieveFormat">
        </el-table-column>
        <el-table-column
            prop="achieveNumber"
            label="数量"
            width="180">
        </el-table-column>
        <el-table-column
            prop="achievePrice"
            label="产值"
            width="180"
            :formatter="priceHandler">
        </el-table-column>
        <el-table-column
            prop="remark"
            label="备注"
            width="180">
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间"
            width="180"
            :formatter="timeFormat2">
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" circle @click="toUpdate(scope.row)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="deleteById(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="sizePage"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {addUserAchieve, deleteUserAchieveById, list, updateUserAchieve} from "@/api/UserAchieve";
import { formateDate } from '@/util/TimeFormat'
import { getAchieveById } from "@/api/Achievement";

export default {
  props: {
    tabs: Object
  },
  name: "Index",
  data(){
    return{
      selectList: [],
      isShow: false,
      form: {},
      updateForm: {},
      selectFormInputNumber: {},
      buttonLoading: false,
      tableData: [],
      rules: {
        achieveTime: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        ],
        achieveId: [
          { required: true, message: '请选择子项目', trigger: 'change' }
        ]
      },
      dialogVisible: false,
      updateButtonLoading: false,

      updateAchieveTime: 0,

      currentPage: 1,
      sizePage: 10,
      totalPage: 0,
    }
  },

  created() {
    this.init()
  },

  methods: {

    selectChangeHandler(val){
      getAchieveById(val).then(res => {
        this.selectFormInputNumber = res.data.data.byId
        var selectFormInputNumber = this.selectFormInputNumber;
        if (selectFormInputNumber.minNumber === null || selectFormInputNumber.minNumber === '' || selectFormInputNumber.minNumber === 0){
          console.log('selectFormInputNumber的最小值是null')
          selectFormInputNumber.minNumber = undefined
        }
        if (selectFormInputNumber.maxNumber === null || selectFormInputNumber.maxNumber === '' || selectFormInputNumber.maxNumber === 0){
          console.log('selectFormInputNumber的最大值是null')
          selectFormInputNumber.maxNumber = undefined
        }
        this.form.achieveNumber = undefined
      })
    },

    priceHandler(row, col, cellValue, index){
      if (cellValue){
        return cellValue.toFixed(2)
      }

    },

    init(){
      var id = this.tabs.id;
      list(id, this.currentPage, this.sizePage).then(res => {
        this.tableData = res.data.data.list
        this.totalPage = res.data.data.total
      })
    },

    toAdd(){
      this.form = {}
      this.isShow = !this.isShow
    },

    handleSizeChange(val){
      list(this.tabs.id, this.currentPage, val).then(res => {
        this.tableData = res.data.data.list
        this.totalPage = res.data.data.total
      })
    },

    handleCurrentChange(val){
      list(this.tabs.id, val, this.sizePage).then(res => {
        this.tableData = res.data.data.list
        this.totalPage = res.data.data.total
      })
    },

    timeFormat(row, col, cellValue, index){
      var date = new Date(cellValue * 1000);
      return formateDate(date, "yyyy-MM")
    },

    timeFormat2(row, col, cellValue, index){
      var date = new Date(cellValue * 1000);
      return formateDate(date, "yyyy-MM-dd")
    },


    achieveFormat(row, col, cellValue, index){
      var achievements = this.tabs.achievements;
      for (let i = 0; i < achievements.length; i++) {
        if (achievements[i].id === cellValue + ""){
          return achievements[i].achieveName
        }
      }
    },

    add(data, form){
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          data.userId = JSON.parse(sessionStorage.getItem('userInfo')).id
          var achieveTime = data.achieveTime;
          data.achieveTime = achieveTime / 1000
          addUserAchieve(data).then(res => {
            this.buttonLoading = false
            this.isShow = !this.isShow
            this.$notify.success(res.data.message)
            this.form = {}
            this.tableData.push(res.data.data.userAchievement)
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    toUpdate(userAchieve){
      this.updateForm = userAchieve
      this.updateAchieveTime = this.updateForm.achieveTime * 1000
      this.dialogVisible = !this.dialogVisible
    },

    update(){
      var updateForm = this.updateForm;
      updateForm.achieveTime = this.updateAchieveTime / 1000
      updateUserAchieve(updateForm).then(res => {
        this.init()
        this.$notify.success(res.data.message)
        this.dialogVisible = !this.dialogVisible
      })
    },

    deleteById(userAchieve){
      this.$confirm('确认删除吗', { title: '提示', confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        deleteUserAchieveById(userAchieve.id).then(res => {
          this.$notify.success(res.data.message)
          this.tableData.splice(this.tableData.indexOf(userAchieve), 1)
        })
      }).catch( _ => {
        this.$notify.warning('取消删除')
      })

    },
  }
}
</script>

<style scoped>
.tabs-button{
  float: left;
  margin: 1% auto;
}

.tabs-add-form{
  width: 100%;
  /*border: 1px solid black;*/
  float: left;
  margin: 1% auto;
}

.tabs-add-form-item{
  float: left;
  margin-left: 1%;
}
</style>